<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addSchoolbag">添加</el-button>
        <el-button type="primary" size="mini" @click="handleDownload">
          激活导入模板
          <i class="el-icon-paperclip el-icon--right"></i>
        </el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="sn码" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" min-width="120" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="140" align="center" prop="sn" label="SN码"></el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="add_time" label="创建时间" min-width="140" align="center">
        <template slot-scope="scope">{{scope.row.add_time| activateTime}}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="redactButton(scope.row)">编辑</el-button>
            <el-button size="mini" @click="getdeleteEbagSn(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>

    <!-- 添加激活书包 -->
    <el-dialog title=" 电子书包SN" :visible.sync="activeFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="25%" @close="addFormclose">
      <el-form :model="addForm" ref="ruleForm">
        <el-form-item label="激活管理:" label-width="100px" v-if="editSubjects">
          <el-radio-group v-model="type" @change="typeChange">
            <el-radio :label="1">单条SN添加</el-radio>
            <el-radio :label="2">批量添加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="SN码:" label-width="100px" prop="sn" v-if="clearShow">
          <el-input v-model="addForm.sn" placeholder="请输入SN码"></el-input>
        </el-form-item>
        <div v-else>
          <el-form-item label="导入文件" label-width="100px" class="snElsx">
            <div class="">
              <el-input autocomplete="off" placeholder="请点击上传，上传xls或xlsx文件" v-model="addForm.file.name"></el-input>
              <upload-excel-component class="flex mrg-top" :loading="!videoFlag" :before-upload="batchUpload" @submitXlsx="submitXlsx">
                <span>{{videoFlag ? '' : goodsData + '%'}}</span>
              </upload-excel-component>
            </div>
          </el-form-item>
          <div v-if="batchShow">
            <el-form-item label="成功导入:" label-width="130px" style="margin-bottom:0">共{{ this.snData.excelSuccess}}条</el-form-item>
            <el-form-item label="导入失败:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.error.length}}条</el-form-item>
            <el-form-item label="不存在的sn:" label-width="130px" style="margin-bottom:0"> 共{{ this.snData.noData.length}}条
              {{ this.snData.noData.length >= 1 ? `( 位于:第${this.snData.noData.toString()}行 )` : ''}}
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="activeFormVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="uploadButton">确 定</el-button>
        <el-button v-else type="primary" size="mini" round @click="geteditEbagSn">编辑</el-button>
      </div>
    </el-dialog>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import UploadExcelComponent from "@/components/UploadExcelSn/index.vue";
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryEbagSnAll, addEbagSnOne, addEbagSnMany, deleteEbagSn, editEbagSn } from "@/api/activationSchoolbag.js";
import deleteDialog from "@/components/deleteDialog";
import { mapState } from 'vuex'
export default {
  components: { dynamicTable, UploadExcelComponent, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "SN码", "创建时间"],
      key: 1,
      colData: [], //动态控制table
      subjectId: 0,
      total: 0,
      select: "", //搜索条件
      searchTable: "",
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: undefined, sn: undefined },
      browserTable: [],
      activeFormVisible: false,
      editSubjects: true,
      addForm: { userId: localStorage.getItem("ID"), sn: '', file: {} },
      type: 1,
      clearShow: true,
      videoFlag: true,
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      batchShow: false,
      snData: {},
    }
  },
  computed: {
    ...mapState({//获取上传滚动条
      goodsData: state => state.user.progress
    })
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getqueryEbagSnAll()
  },
  methods: {
    //删除
    getdeleteEbagSn(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { id: this.deleteDialogs.deleteId, userId: localStorage.getItem("ID") }
      deleteEbagSn(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryEbagSnAll()
      })
    },
    //编辑信息m
    redactButton(row) {
      this.editSubjects = false
      this.activeFormVisible = true
      this.addForm.sn = row.sn
      this.subjectId = row.id
    },
    geteditEbagSn() {
      let params = { userId: localStorage.getItem("ID"), sn: this.addForm.sn, id: this.subjectId }
      editEbagSn(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryEbagSnAll()
        this.activeFormVisible = false
      }).catch(err => {
        this.activeFormVisible = false
      })
    },
    batchUpload(file) {
      this.addForm.file = file
    },
    submitXlsx(event) {
      var fd = new FormData()
      fd.append('file', this.addForm.file)
      fd.append('userId', localStorage.getItem("ID"))
      this.videoFlag = false
      addEbagSnMany(fd).then(res => {
        console.log('添加成功', res.data)
        this.snData = res.data
        this.batchShow = true
        this.$message.success(res.msg)
        this.getqueryEbagSnAll()
        this.videoFlag = true
      }).catch(err => {
        this.videoFlag = true
      })
    },
    //导入确定事件
    uploadButton() {
      if (this.type == 2) {
        if (this.addForm.file instanceof File) {
          if (this.batchShow) {
            this.activeFormVisible = false
          } else {
            this.$message('存在导入文件未上传，请确认是否需要上传。')
          }
        } else {
          this.activeFormVisible = false
        }
      } else {
        this.getaddEbagSnOne()
      }
    },
    getaddEbagSnOne() {
      let addForm = JSON.parse(JSON.stringify(this.addForm))
      addEbagSnOne(addForm).then(res => {
        this.$message.success(res.msg)
        this.getqueryEbagSnAll()
        this.activeFormVisible = false
      }).catch(err => {
        this.getqueryEbagSnAll()
        this.activeFormVisible = false
      })
    },
    addSchoolbag() {
      this.activeFormVisible = true
      this.editSubjects = true
    },
    typeChange(val) {
      val == 1 ? this.clearShow = true : this.clearShow = false
    },
    getqueryEbagSnAll() {
      queryEbagSnAll(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
        this.total = 0
      });
    },
    handleDownload() {
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["SN"];
        const filterVal = ["sn"];
        const list = [{ "sn": 'QNS2HIYS0003' }]
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({ header: tHeader, data, filename: '激活导入模板' });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryEbagSnAll();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryEbagSnAll();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: undefined, sn: undefined }
      this.getqueryEbagSnAll()
    },
    addFormclose() {
      this.$nextTick(() => {
        this.addForm = { userId: localStorage.getItem("ID"), sn: '', file: {} }
        this.clearShow = true
        this.videoFlag = true
        this.batchShow = false
        this.type = 1
      })
    },
     idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.type = 1
          this.listQuery.sn = this.searchTable
          break;
      }
      this.getqueryEbagSnAll();
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
</style>